package com.learn.xueer.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.media.MediaRecorder
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import android.util.Log
import android.view.LayoutInflater
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.gson.Gson
import com.learn.xueer.R
import com.learn.xueer.app.base.BaseActivity1
import com.learn.xueer.app.ext.init
import com.learn.xueer.app.util.MediaPlayerProgressListener
import com.learn.xueer.data.model.bean.HearSayQuestionResourceItem
import com.learn.xueer.databinding.ActivityHearSayTestBinding
import com.learn.xueer.ui.adapter.TopicAdapter
import com.learn.xueer.ui.viewmodel.RequestHearViewModel
import kotlinx.android.synthetic.main.activity_hear_say_test.nextButton
import kotlinx.android.synthetic.main.activity_hear_say_test.questionTrunk
import kotlinx.android.synthetic.main.activity_hear_say_test.testTemplate
import kotlinx.android.synthetic.main.activity_hear_say_test.trunkImage
import kotlinx.coroutines.runBlocking
import me.hgj.jetpackmvvm.ext.parseState
import java.io.File
import java.io.IOException
import java.util.Locale

class HearSayTestActivity : BaseActivity1<RequestHearViewModel, ActivityHearSayTestBinding>() {

    private lateinit var id: String
    private lateinit var title: String
    private lateinit var resMain: String
    private lateinit var templateUrl: String
    private lateinit var trunkUrl: String
    private var mediaPlayer: MediaPlayer? = null
    private var mediaPlayerProgressListener: MediaPlayerProgressListener? = null
    private lateinit var items: ArrayList<HearSayQuestionResourceItem>
    private val topicAdapter: TopicAdapter by lazy { TopicAdapter(arrayListOf()) }
    private var currentPosition = 0
    private var currentPlayUrl = ""
    private var countDownTimer: CountDownTimer? = null
    private var recorder: MediaRecorder? = null
    private var currentFileType = 2
    private lateinit var dialog: BottomSheetDialog
    private var answerList: ArrayList<String> = arrayListOf()
    private lateinit var outPutFile: File

    override fun initView(savedInstanceState: Bundle?) {
        addLoadingObserve(mViewModel)
        id = intent.getStringExtra("id")!!
        title = intent.getStringExtra("title")!!
        mViewModel.testTitle.set(title)
        mViewModel.testIcon.set(R.mipmap.icon_read)
        mViewBind.viewmodel = mViewModel
        mViewBind.click = ProxyClick()

        mViewModel.secondDurationStr.set("正在播放原声  剩余")

        mViewModel.hearsayQuestionReq(id)
    }

    private fun initMediaPlayer(url: String) {
        runOnUiThread {
            if (url == templateUrl) {
                testTemplate.setTextColor(ContextCompat.getColor(this, R.color._333333))
                questionTrunk.setTextColor(ContextCompat.getColor(this, R.color.b5b5b5))
            } else {
                questionTrunk.setTextColor(ContextCompat.getColor(this, R.color._333333))
                testTemplate.setTextColor(ContextCompat.getColor(this, R.color.b5b5b5))
            }
        }
        mViewModel.secondDurationStr.set("正在播放原声  剩余")
        if (mediaPlayer != null) {
            mediaPlayer?.release()
            mediaPlayer = null
        }
        if (mediaPlayerProgressListener != null) {
            mediaPlayerProgressListener?.stopProgressListener()
            mediaPlayerProgressListener = null
        }
        currentPlayUrl = url
        mediaPlayer = MediaPlayer.create(this, Uri.parse(url))
        mediaPlayerProgressListener = MediaPlayerProgressListener(mediaPlayer,
            object : MediaPlayerProgressListener.OnProgressListener {
                override fun onProgress(progress: Int) {
                    val duration = mediaPlayer?.duration
                    val currentSecond = duration!! - progress
                    val second = currentSecond / 1000

                    runOnUiThread {
                        mViewModel.secondDuration.set(second.toString() + "s")
                    }
                }
            })

        mediaPlayer?.setOnCompletionListener {
            mediaPlayerProgressListener?.stopProgressListener()
            mediaPlayer?.release()
            if (currentPlayUrl == templateUrl && currentFileType == 2) {
                initMediaPlayer(trunkUrl)
            } else {

            }
        }

        mediaPlayer?.start()
    }

    override fun onPause() {
        super.onPause()
        if (mediaPlayer != null) {
            if (mediaPlayer!!.isPlaying) {
                mediaPlayer!!.pause()
            }
        }

    }

    override fun onResume() {
        super.onResume()
        if (mediaPlayer != null) {
            mediaPlayer!!.start()
        }
    }

    override fun createObserver() {
        mViewModel.hearsayQuestionResult.observe(this, Observer { resultState ->
            parseState(resultState, {
                items =
                    it?.resource?.items as ArrayList<HearSayQuestionResourceItem>? ?: arrayListOf()
                topicAdapter.setList(items)
                mViewModel.testTemplate.set(it?.resource!!.items[0].templateSettings.content)
                mViewModel.questionTrunk.set(it.resource.items[0].questions[0].trunk.body)
                resMain = it.resmain
                templateUrl = resMain + it.resource.items[0].templateSettings.audioUrl
                trunkUrl =
                    resMain + it.resource.items[0].questions[0].trunk.attachments[0].url
                currentFileType = it.resource.items[0].questions[0].trunk.attachments[0].fileType
                if (currentFileType == 1) {
                    trunkImage.visibility = VISIBLE
                    questionTrunk.visibility = GONE
                    mViewModel.questionTrunkUrl.set(trunkUrl)
                } else {
                    trunkImage.visibility = GONE
                    questionTrunk.visibility = VISIBLE
                    mViewModel.questionTrunkUrl.set(trunkUrl)
                }
                runBlocking {
                    initMediaPlayer(templateUrl)
                }
                testTemplate.setTextColor(ContextCompat.getColor(this, R.color._333333))
                questionTrunk.setTextColor(ContextCompat.getColor(this, R.color.b5b5b5))
            }, {})
        })
    }

    inner class ProxyClick {
        fun returnBack() {
            finish()
        }

        @SuppressLint("MissingInflatedId")
        fun copy() {
            dialog = BottomSheetDialog(
                this@HearSayTestActivity,
                R.style.BottomSheetDialog
            )
            val inflate = LayoutInflater.from(this@HearSayTestActivity)
                .inflate(R.layout.topic_list_dialog, null)
            val recyclerView: RecyclerView = inflate.findViewById(R.id.topicRecyclerView)
            val btnFinish: TextView = inflate.findViewById(R.id.btnFinish)

            recyclerView.init(LinearLayoutManager(this@HearSayTestActivity), topicAdapter)
            topicAdapter.setOnItemClickListener { adapter, view, position ->
                if (countDownTimer != null) {
                    countDownTimer?.cancel()
                    countDownTimer = null
                }
                if (recorder != null) {
                    recorder?.stop()
                    recorder?.release()
                    recorder = null
                }
                if (mediaPlayer != null) {
                    mediaPlayer?.release()
                    mediaPlayer = null
                    mediaPlayerProgressListener?.stopProgressListener()
                }
                cutTopic(position)
                dialog.dismiss()
            }

            btnFinish.setOnClickListener {
                val intent = Intent(this@HearSayTestActivity, SubmitHearSayActivity::class.java)
                intent.putExtra("items",Gson().toJson(items))
                intent.putExtra("title", title)
                intent.putExtra("id", id)
                intent.putExtra("resMain", resMain)
                startActivity(intent)
            }

            dialog.setContentView(inflate)
            dialog.show()
        }

        @RequiresApi(Build.VERSION_CODES.M)
        fun nextStep() {
            if (countDownTimer != null) {
                countDownTimer?.cancel()
                countDownTimer = null
            }
            if (recorder != null) {
                stopRecord()
                return
            }

            if (currentPosition == items.size - 1) {
                val intent = Intent(this@HearSayTestActivity, SubmitHearSayActivity::class.java)
                intent.putExtra("items",Gson().toJson(items))
                intent.putExtra("title", title)
                intent.putExtra("id", id)
                intent.putExtra("answerList", Gson().toJson(answerList))
                intent.putExtra("resMain", resMain)
                startActivity(intent)
                return
            }

            if (currentPlayUrl.isNotEmpty() && currentPlayUrl == templateUrl) {
                if (currentFileType == 2) {
                    questionTrunk.setTextColor(
                        ContextCompat.getColor(
                            this@HearSayTestActivity,
                            R.color._333333
                        )
                    )
                    testTemplate.setTextColor(
                        ContextCompat.getColor(
                            this@HearSayTestActivity,
                            R.color.b5b5b5
                        )
                    )
                    initMediaPlayer(trunkUrl)
                } else {
                    startPrepare()
                }
            } else if (currentPlayUrl.isNotEmpty() && currentPlayUrl == trunkUrl) {
                startPrepare()
            } else if (currentPlayUrl == "") {
                if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(arrayOf<String>(Manifest.permission.RECORD_AUDIO), 1)
                } else {
                    startRecord()
                }
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun startPrepare() {
        if (mediaPlayer != null) {
            mediaPlayer?.release()
            mediaPlayer = null
            mediaPlayerProgressListener?.stopProgressListener()
        }
        currentPlayUrl = ""
        mViewModel.testIcon.set(R.mipmap.icon_prepare)
        mViewModel.secondDurationStr.set("准备时间  剩余")
        val readyTime =
            items[currentPosition].templateSettings.listeningAndSpeakingRule.readyTime * 1000
        countDownTimer = object : CountDownTimer(readyTime.toLong(), 1000) {
            override fun onTick(millisUntilFinished: Long) {
                mViewModel.secondDuration.set("${millisUntilFinished / 1000}s")
            }

            override fun onFinish() {
                countDownTimer?.cancel()
                countDownTimer = null

                if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(arrayOf<String>(Manifest.permission.RECORD_AUDIO), 1)
                } else {
                    startRecord()
                }

            }
        }
        countDownTimer?.start()
    }

    private fun startRecord() {
        var sdcardfile = getExternalFilesDir(null)

        mViewModel.secondDurationStr.set("录音时间  剩余")
        nextButton.text = "完成录音"
        mViewModel.testIcon.set(R.mipmap.icon_record)
        val answerTime =
            items[currentPosition].templateSettings.listeningAndSpeakingRule.answerTime * 1000
        countDownTimer = object : CountDownTimer(answerTime.toLong(), 1000) {
            @RequiresApi(Build.VERSION_CODES.O)
            override fun onTick(millisUntilFinished: Long) {
                mViewModel.secondDuration.set("${millisUntilFinished / 1000}s")
                recorder = MediaRecorder()

                //设置音频源
                recorder!!.setAudioSource(MediaRecorder.AudioSource.MIC)
                //设置输出格式
                recorder!!.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
                //设置音频编码
                recorder!!.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
                try {
                    outPutFile =
                        File.createTempFile("$title${currentPosition + 1}", ".mp3", sdcardfile)
                    //设置录音保存路径
                    recorder!!.setOutputFile(outPutFile)
                    //准备和启动录制音频
                    recorder!!.prepare()
                    recorder!!.start()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }

            override fun onFinish() {
                countDownTimer?.cancel()
                countDownTimer = null
                stopRecord()
            }
        }
        countDownTimer?.start()
    }

    //停止录音
    private fun stopRecord() {
        nextButton.text = "下一步"
        try {
            recorder!!.stop()
            answerList.add(outPutFile.path)
            recorder!!.release()
            recorder = null
            cutTopic()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun cutTopic(position: Int? = null) {
        if (position != null) {
            currentPosition = position
        } else {
            if (currentPosition < items.size - 1) {
                currentPosition += 1
            }
        }

        mViewModel.testTemplate.set(items[currentPosition].templateSettings.content)
        mViewModel.questionTrunk.set(items[currentPosition].questions[0].trunk.body)
        templateUrl = resMain + items[currentPosition].templateSettings.audioUrl
        trunkUrl =
            resMain + items[currentPosition].questions[0].trunk.attachments[0].url
        currentFileType = items[currentPosition].questions[0].trunk.attachments[0].fileType
        if (currentFileType == 1) {
            trunkImage.visibility = VISIBLE
            questionTrunk.visibility = GONE
            mViewModel.questionTrunkUrl.set(trunkUrl)
        } else {
            trunkImage.visibility = GONE
            questionTrunk.visibility = VISIBLE
            mViewModel.questionTrunkUrl.set(trunkUrl)
        }
        initMediaPlayer(templateUrl)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mediaPlayer != null) {
            mediaPlayerProgressListener?.stopProgressListener()
            mediaPlayer?.stop()
            mediaPlayer?.release()
        }
        if (countDownTimer != null) {
            countDownTimer?.cancel()
            countDownTimer = null
        }
        mediaPlayer = null
    }

    //动态申请权限的回调函数
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startRecord()
        } else {
            Toast.makeText(this, "用户已拒绝权限", Toast.LENGTH_SHORT).show()
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
}